package com.ymsoft.myerp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ymsoft.myerp.common.BaseController;
import com.ymsoft.myerp.common.DTO;
import com.ymsoft.myerp.common.RetEnum;
import com.ymsoft.myerp.entity.Role;
import com.ymsoft.myerp.entity.User;
import com.ymsoft.myerp.service.IRoleService;
import com.ymsoft.myerp.service.IUserService;
import com.ymsoft.myerp.util.GoogleAuthenticator;
import com.ymsoft.myerp.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ymsoft
 * @since 2020-04-12
 */
@Controller
@RequestMapping("/myerp/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IRoleService iRoleService;

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(User user, @RequestParam int page, @RequestParam int limit) {//layui默认分页参数page和limit
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(user.getUsername())) {
            queryWrapper.like("username", user.getUsername());
        }
        if(user.getId() != null) {
            queryWrapper.eq("id", user.getId());
        }
        queryWrapper.orderByDesc("id");
        // 查询第1页，每页返回5条
        Page<User> userPage = new Page<>(page, limit);
        IPage<User> iPage = iUserService.page(userPage, queryWrapper);
        //需要配置mybatis plus的分页插件，否则无法正常分页
        return ResponseEntity.ok(DTO.retSuccess(iPage.getRecords(), (int)iPage.getTotal()));
    }


    @RequestMapping("/all")
    @ResponseBody
    public DTO<?> all() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        List<User> list = iUserService.list(queryWrapper);
        return DTO.retSuccess(list);
    }

    @PostMapping("/save")
    @ResponseBody
    public DTO<?> add(@Valid User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        int count = iUserService.count(queryWrapper);
        if(count > 0) {
            return DTO.ret(RetEnum.RET_USER_NAME_USED);
        }

        if(StringUtils.isNotBlank(user.getPassword())) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            final String rawPassword = user.getPassword();
            user.setPassword(encoder.encode(rawPassword));
        }

        boolean isOk = iUserService.save(user);
        if(isOk) {
            return DTO.retSuccess();
        }
        return DTO.retFailed();
    }

    @PostMapping("/reset_password")
    @ResponseBody
    public DTO<?> resetPassword(@RequestParam int id) {
        User user = iUserService.getById(id);
        if(user != null) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            final String rawPassword = "123456";
            user.setPassword(encoder.encode(rawPassword));
            boolean isOk = iUserService.updateById(user);
            if(isOk) {
                return DTO.retSuccess();
            }
        }
        return DTO.retFailed();
    }

    @PostMapping("/auth_code")
    @ResponseBody
    public DTO<?> authCode(@RequestParam int id) {
        User user = iUserService.getById(id);
        if(user != null) {
            if(StringUtils.isNotBlank(user.getGoogleKey())) {
                String secret = user.getGoogleKey();
                String username = user.getUsername();
                String url = GoogleAuthenticator.getQRBarcode(username, secret);
                Map<String, String> map = new HashMap<>();
                map.put("url", url);
                map.put("key", secret);
                return DTO.retSuccess(map);
            } else {
                String secret = GoogleAuthenticator.generateSecretKey();
                user.setGoogleKey(secret);
                boolean isOk = iUserService.updateById(user);
                if(isOk) {
                    String username = user.getUsername();
                    String url = GoogleAuthenticator.getQRBarcode(username, secret);
                    Map<String, String> map = new HashMap<>();
                    map.put("url", url);
                    map.put("key", secret);
                    return DTO.retSuccess(map);
                }
            }

        }
        return DTO.retFailed();
    }

    /**
     *
     * @param request
     * @return
     */
    @RequestMapping("/listALL")
    @ResponseBody
    public DTO<?> List(HttpServletRequest request){
        List<User> users =iUserService.list();
        return DTO.retSuccess(users);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public DTO<?> delete(@RequestParam int id){
        User user = iUserService.getById(id);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", user.getRoleId());
        queryWrapper.eq("name", "ADMIn");
        int count = iRoleService.count(queryWrapper);
        if(count > 0) {
            return DTO.ret(RetEnum.RET_COMM_ADMIN_ROLE_FORBIDDEN_TO_DELETE);
        }
        boolean flag = iUserService.removeById(id);
        if(flag) {
            return DTO.retSuccess();
        }
        return DTO.retFailed();
    }
}
